<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Babylon.js 物体碰撞检测</title>
    <!-- 引入 Babylon.js 库 -->
    <script src="https://cdn.babylonjs.com/babylon.js"></script>
    <script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        #renderCanvas {
            width: 100%;
            height: 100%;
            touch-action: none;
        }

        #message {
            position: absolute;
            top: 10px;
            left: 10px;
            font-size: 20px;
            color: white;
        }
    </style>
</head>

<body>
<canvas id="renderCanvas"></canvas>
<div id="message"></div>
<script>
    // 获取 canvas 元素
    const canvas = document.getElementById('renderCanvas');
    const messageDiv = document.getElementById('message');

    // 创建 Babylon.js 引擎
    const engine = new BABYLON.Engine(canvas, true);

    // 创建场景
    const createScene = function () {
        const scene = new BABYLON.Scene(engine);

        // 创建相机
        const camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, BABYLON.Vector3.Zero(), scene);
        camera.setPosition(new BABYLON.Vector3(0, 5, -10));
        camera.attachControl(canvas, true);

        // 创建光源
        const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);

        // 创建两个球体
        const sphere1 = BABYLON.MeshBuilder.CreateSphere("sphere1", { diameter: 1 }, scene);
        sphere1.position = new BABYLON.Vector3(-2, 0, 0);

        const sphere2 = BABYLON.MeshBuilder.CreateSphere("sphere2", { diameter: 1 }, scene);
        sphere2.position = new BABYLON.Vector3(2, 0, 0);

        // 定义球体的运动速度
        const sphere1Speed = new BABYLON.Vector3(0.01, 0, 0);
        const sphere2Speed = new BABYLON.Vector3(-0.01, 0, 0);

        // 碰撞检测函数

        // 每帧更新函数
        scene.registerBeforeRender(function () {
            // 更新球体位置
            sphere1.position.addInPlace(sphere1Speed);
            sphere2.position.addInPlace(sphere2Speed);

            if( sphere1.position.x>2){
                sphere1.position.x=0
            }
            if( sphere2.position.x<-2){
                sphere2.position.x=0
            }

            // 检测碰撞
            if (sphere1.intersectsMesh(sphere2)) {
                messageDiv.textContent = '碰撞发生！';
            } else {
                messageDiv.textContent = '未碰撞';
            }
        });

        return scene;
    };

    // 创建场景
    const scene = createScene();

    // 运行渲染循环
    engine.runRenderLoop(function () {
        scene.render();
    });

    // 处理窗口大小变化
    window.addEventListener('resize', function () {
        engine.resize();
    });
</script>
</body>

</html>
